package com.yixun.qfbao.hander;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.yixun.qfbao.api.service.CompanyService;
import com.yixun.qfbao.api.service.WxTemplateMsgService;
import com.yixun.qfbao.api.service.impl.WxTemplateMsgServiceImpl;
import com.yixun.qfbao.dto.base.BaseRequestDTO;
import com.yixun.qfbao.dto.base.BaseResponseDTO;
import com.yixun.qfbao.enums.QfSmsTemplateEnum;
import com.yixun.qfbao.hander.base.CommonAbstractHander;
import com.yixun.qfbao.mapper.SubscriptionMapper;
import com.yixun.qfbao.model.CheckRecord;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.Subscription;
import com.yixun.qfbao.model.dto.PartnerInfoDto;
import com.yixun.qfbao.model.dto.SubscriptionDto;
import com.yixun.qfbao.model.enums.CheckStatusEnum;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.ModelTypeEnum2;
import com.yixun.qfbao.model.enums.SMSTypeEnum;
import com.yixun.qfbao.model.enums.SystemIdEnum;
import com.yixun.qfbao.service.CheckRecordService;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.service.ValidateCodeService;
import com.yixun.qfbao.utils.LoginUtils;
import com.yixun.qfbao.vo.AgentCompanyCheckReqVo;
import com.yixun.qfbao.xf.model.enums.ResultEnum;

/**
 * @author zilong.liu
 * @date 2020-12-16
 *
 * desc:
 *     	人员审核
 */
@Service("agentCompanyCheckHander")
public class AgentCompanyCheckHander extends CommonAbstractHander{

	
	@Autowired
	CheckRecordService checkRecordService;
	
	@Autowired
	CompanyService companyService;
	
	@Autowired
	PartnerInfoService partnerInfoService;
	
	@Autowired
	WxTemplateMsgService wxTemplateMsgService;
	
	@Autowired
	ValidateCodeService validateCodeService;
	
	@Autowired
	SubscriptionMapper subscriptionMapper;
	
	@Autowired
	LoginUtils loginUtils;
	
	@Override
	@Transactional
	public BaseResponseDTO doBusiness(BaseRequestDTO reqDto) {
		BaseResponseDTO<String> res = new BaseResponseDTO<>();
		
		AgentCompanyCheckReqVo reqVo = (AgentCompanyCheckReqVo)reqDto;
		String checkStatus = reqVo.getParams().getCheckStatus();
		if(!CheckStatusEnum.FAILURE.getNo().equals(checkStatus) &&
				!CheckStatusEnum.SUCCESS.getNo().equals(checkStatus)) {
			res.setErrorMsg("未勾选审核状态");
			res.setResult(ResultEnum.FAIL.getNo());
			return res;
		}
		long checkCompanyId = reqVo.getParams().getCheckCompanyId();
		String loginType = reqVo.getParams().getLoginType();
		String companyUuid = reqVo.getParams().getCompanyUuid();
		String userId = reqVo.getParams().getUserId();
		
		//登录人信息
		PartnerInfo loginPartnerInfo = loginUtils.getUser(userId);
		if(loginPartnerInfo == null) {
			res.setErrorMsg("人员信息有误");
			res.setResult(ResultEnum.FAIL.getNo());
			return res;
		}
		
		// 1、校验
		Company company = companyService.getCompanyById(checkCompanyId);
		if(company == null) {
			res.setErrorMsg("审核公司ID有误");
			res.setResult(ResultEnum.FAIL.getNo());
			return res;
		}
		
		CheckRecord entity = new CheckRecord();
		entity.setRelId(checkCompanyId);
		entity.setType(ModelTypeEnum2.COMPANY.getNo());
		// 检查当前人员状态，避免多次审核
		List<CheckRecord> checkRecordList = checkRecordService.selectByDto(entity);
		if(!CollectionUtils.isEmpty(checkRecordList)) {
			res.setErrorMsg("已审核，请勿重复审核");
			res.setResult(ResultEnum.FAIL.getNo());
			return res;
		}
		
		String remark = reqVo.getParams().getRemark();
		// 2、 添加审核记录
		entity.setStatus(checkStatus);
		entity.setRemark(remark);
		entity.setCreateUserId(userId);
		checkRecordService.add(entity);
		// 3、更新公司状态
		Company editCompany = new Company();
		editCompany.setId(checkCompanyId);
		editCompany.setCity(company.getCity());
		editCompany.setDomain(company.getDomain());
		editCompany.setMerchantCode(company.getMerchantCode());
		editCompany.setCreateUserId(company.getCreateUserId());
		editCompany.setChargeMan(company.getChargeMan());
		editCompany.setPhone(company.getPhone());
		editCompany.setStatus(checkStatus);
		companyService.edit(editCompany);
		// 4、更新人员状态
		PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
		partnerInfoDto.setId(company.getCreateUserId());
		partnerInfoDto.setCheckStatus(checkStatus);
		partnerInfoDto.setDelFlag(CheckStatusEnum.FAILURE.getNo().equals(checkStatus)? 
				DelFlagEnum.DEL.getNo(): DelFlagEnum.UNDEL.getNo());
		partnerInfoService.update(partnerInfoDto);
		
		PartnerInfo partnerInfo = partnerInfoService.selectById(company.getCreateUserId());
		// 5、下发审核消息
		wxTemplateMsgService.sendCheckTemplateMsg(companyUuid, partnerInfo, 
				CheckStatusEnum.SUCCESS.getNo().equals(checkStatus),
				remark, WxTemplateMsgServiceImpl.CHECK_TYPE_ARRAY[1]);
		
		// 6、下发审核短信
		// 拼接下发短信的内容
		String messageContent = "";
		String msgId = "";
		String smsDesc = "";
		String[] msgs = null;
		if(CheckStatusEnum.SUCCESS.getNo().equals(checkStatus)) {
			SubscriptionDto subscriptionDto = new SubscriptionDto();
			subscriptionDto.setCompanyUuid(companyUuid);
			subscriptionDto.setSystemId(SystemIdEnum.WEAPP_AGENCY.getCode());
			subscriptionDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			Subscription subscription = subscriptionMapper.selectByDto(subscriptionDto);
			String appName = subscription.getAppName();
			messageContent = "合作机构申请成功，你的账号" + company.getPhone() + "已被注册为管理员，可正常使用" + appName + "。";
			msgId = QfSmsTemplateEnum.COMPANY_REGESIT_FAIL.getId();
			smsDesc = SMSTypeEnum.TYPE_17.getDes();
			msgs = new String[] {company.getPhone(), appName};
		}else if(CheckStatusEnum.FAILURE.getNo().equals(checkStatus)) {
			messageContent = "合作机构申请不通过。";
			if(StringUtils.isNotEmpty(remark)) {
				messageContent += "原因是" + remark;
			}
			smsDesc = SMSTypeEnum.TYPE_18.getDes();
			msgId = QfSmsTemplateEnum.COMPANY_REGESIT_SUCCESS.getId();
			msgs = new String[] {remark};
		}
		validateCodeService.sendAndSaveSmsmsg(company.getPhone(), messageContent, 
				msgId, smsDesc, loginType, companyUuid, "", loginPartnerInfo.getHigherid(), msgs);
		
		res.setResData("成功");
		res.setResult(ResultEnum.SUCCESS.getNo());
		return res;
	}
	

}
